#!/usr/bin/env python
# coding:utf-8
from PoboAPI import *
import datetime
import numpy as np
#tick级别的盘口策略例子，在买卖盘价差达到条件时进行交易
#开始时间，用于初始化一些参数
def OnStart(context) :
    print("I\'m starting...")
    #登录交易账号，需在主页用户管理中设置账号，并把期货测试替换成您的账户名称
    g.exchange="SHFE"
    g.product="ag"
    context.myacc = None
    if "回测期货" in context.accounts :
        print("登录交易账号[回测期货]")
        if context.accounts["回测期货"].Login() :
            context.myacc = context.accounts["回测期货"]

def OnMarketQuotationInitialEx(context, exchange,daynight):
    if exchange != g.exchange:
        return
    #获取主力合约
    g.code = GetMainContract(g.exchange, g.product,20)
    g.spreadthreshold=4
    g.minchange=GetVarietyInfo(g.exchange,g.product)["最小变动价位"]
    #订阅K线数据，用于驱动OnBar事件
    #SubscribeBar(g.code, BarType.Day)
    SubscribeQuote(g.code)
    
    g.openflag=1 #开仓标志，1为可开仓，0为不可开仓
    
#实时行情事件，当有新行情出现时调用该事件

def OnQuote(context,code) :
    #print('调用到OnQuote事件')
    dyndata = GetQuote(g.code)
    now1 = dyndata.now
    
    bidprice=dyndata.bidprice(0)
    
    askprice=dyndata.askprice(0)
    
    spread=askprice-bidprice #计算买卖盘价差
    
    
    if spread>=g.spreadthreshold and g.openflag==1: #买开仓
        
        QuickInsertOrder(context.myacc,g.code,'buy','open',bidprice,10)
        
        print("发出买入委托 价差"+str(spread))
        
        g.openflag=0
        
        
def OnTradeDeal(context, AccountName, trade) :
    print("TradeDealed on " + str(trade.id) + " on " + str(AccountName))
    
    if trade.bstype.BuySellFlag=="0" and trade.bstype.OffsetFlag=="0": #监控买开仓
        
        QuickInsertOrder(context.myacc,g.code,'sell','close',trade.price+g.minchange,trade.volume)
        print("发出卖平委托")
                               
        
        
        

# def OnBar(context,code,bartype):
#     #过滤掉不需要的行情通知
#     if code != g.code:
#         return
#     dyndata = GetQuote(g.code)
#     #计算均线
#     MA = GetIndicator("MA",code,params=(5,10),bar_type = BarType.Day)
#     MA1 = MA["MA(5)"]
#     MA2 = MA["MA(10)"]
#     if len(MA2)<2:
#         return
#     #ma1上穿ma2时买入螺纹主力1手
#     elif MA1[-1] >= MA2[-1] and MA1[-2]<MA2[-2]:
#         QuickInsertOrder(context.myacc,g.code,'buy','open',dyndata.now,10)
#     #ma1下穿ma2时卖出平仓
#     elif MA1[-1] <= MA2[-1] and MA1[-2]>MA2[-2]:
#         QuickInsertOrder(context.myacc,g.code,'sell','close',dyndata.now,10)
        
